﻿using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.MessageHandlers;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace WeiTao.Controllers
{
    public class WeiXin2Controller : ApiController
    {
        public readonly string Token = "weixin";

        public HttpResponseMessage Get(string signature, string timestamp, string nonce, string echostr)
        {
            if (CheckSignature.Check(signature, timestamp, nonce, Token))
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(echostr)
                };
                return response;
            }
            else
            {
                var response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                {
                    Content = new StringContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token))
                };
                return response;
            }
        }

        public HttpResponseMessage Post(string signature, string timestamp, string nonce, string echostr)
        {
            if (!CheckSignature.Check(signature, timestamp, nonce, Token))
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token))
                };
                return response;
            }
            else
            {
                var messageHandler = new MyMessageHandler(Request.Content.ReadAsStreamAsync().Result);
                messageHandler.Execute();//执行微信处理过程

                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(messageHandler.ResponseDocument.ToString())
                };
                return response;
            }
        }
    }

    public class MyMessageHandler : MessageHandler
    {
        public MyMessageHandler(Stream inputStream)
            : base(inputStream)
        {

        }

        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnEvent_EnterRequest(RequestMessageEvent_Enter requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnLocationRequest(RequestMessageLocation requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnEventRequest(RequestMessageEventBase requestMessage)
        {
            return base.OnEventRequest(requestMessage);
        }

        public override IResponseMessageBase OnLinkRequest(RequestMessageLink requestMessage)
        {
            throw new NotImplementedException();
        }

        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageNews>(RequestMessage);
            if (requestMessage.Content == "优户科技")
            {
                responseMessage.Articles.Add(new Article()
                {
                    Title = "你好：" + requestMessage.Content,
                    Description = "优户软件是军用技术民用化、大型系统产品化、复杂系统简单化的成果.",
                    PicUrl = "http://www.uuhooo.com/templets/default/images/logo.png",
                    Url = "http://www.uuhooo.com"
                });
            }
            else if (requestMessage.Content == "小虫米子")
            {
                responseMessage.Articles.Add(new Article()
                {
                    Title = "你好：" + requestMessage.Content,
                    Description = "小虫米子 为您带来时尚最前沿，高端的女装服饰，优雅女人，从这里开始~~~~ 装点衣橱，点亮人生",
                    PicUrl = "http://logo.taobaocdn.com/shop-logo/6e/9f/T1XLSaXrxeXXaCwpjX",
                    Url = "http://tone-elegancy.taobao.com/"
                });
            }
            else if (requestMessage.Content.Length > 0)
            {
                try
                {
                    string url = "http://gw.api.taobao.com/router/rest?";
                    string appkey = "21441486";
                    string appsecret = "f3d023d8d29d550948a0b0a38f2b972d";

                    ITopClient client = new DefaultTopClient(url, appkey, appsecret);
                    ShopGetRequest req = new ShopGetRequest();
                    req.Fields = "sid,cid,title,nick,desc,bulletin,pic_path,created,modified";
                    req.Nick = requestMessage.Content.Trim();
                    ShopGetResponse response = client.Execute(req);

                    responseMessage.Content = "";
                    responseMessage.Articles.Add(new Article()
                    {
                        Title = response.Shop.Nick,
                        Description = response.Shop.Title,
                        PicUrl = "http://logo.taobaocdn.com/shop-logo" + response.Shop.PicPath,
                        Url = string.Format("shop{0}.taobao.com", response.Shop.Sid)
                    });
                }
                catch (Exception ex)
                {
                    responseMessage.Content = "";
                    responseMessage.Articles.Add(new Article()
                    {
                        Title = "亲，你好,没有找到你需要的淘宝店铺信息.--" + requestMessage.Content,
                        Description = "请输入某个淘宝掌柜昵称,即可查看店铺信息.比较知名的店铺有\r\n小虫米子,水无香淘衣坊,圣水无痕等",
                        PicUrl = "http://res.wx.qq.com/mpres/htmledition/images/new/mp_index_banner.jpg",
                        Url = "http://ascent.azurewebsites.net"
                    });
                }
            }
            else
            {
                responseMessage.Content = "";
                responseMessage.Articles.Add(new Article()
                {
                    Title = "亲，你好,没有找到你需要的淘宝店铺信息.--" + requestMessage.Content,
                    Description = "请输入某个淘宝掌柜昵称,即可查看店铺信息.比较知名的店铺有\r\n小虫米子,水无香淘衣坊,圣水无痕等",
                    PicUrl = "http://res.wx.qq.com/mpres/htmledition/images/new/mp_index_banner.jpg",
                    Url = "http://ascent.azurewebsites.net"
                });
            }

            //using (var context = new WeiXinContext())
            //{
            //    context.RequestMessageTexts.Add(requestMessage);
            //    //context.ResponseMessageTexts.Add(responseMessage);
            //    context.SaveChanges();
            //};

            return responseMessage;
        }

        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            throw new NotImplementedException();
        }
    }

    public class WeiXinContext : DbContext
    {
        public DbSet<Info> Infos { get; set; }
        public DbSet<RequestMessageText> RequestMessageTexts { get; set; }
        //public DbSet<ResponseMessageText> ResponseMessageTexts { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //
            modelBuilder.Entity<RequestMessageText>().HasKey(id => id.MsgId);
            modelBuilder.Entity<RequestMessageText>().Property(t => t.MsgId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            //modelBuilder.Entity<ResponseMessageText>().HasKey(id => new {id.ToUserName, id.CreateTime });

            modelBuilder.Entity<Info>().HasKey(id => id.Id);
        }
    }
    public class Info
    {
        public int Id { get; set; }
        public DateTime InfoDateTime { get; set; }
    }
}
